const zoroDB = require('../util/zoroDB'),
  log = require('../util/log'),
  SQL_TABLE = 'html',
  SQL_SELECT = 'select html_id as htmlId, html, time from ' + SQL_TABLE,
  SQL_FIELDS = ['html_id', 'html', 'time', 'needLogin', 'isMarkdown'];

exports.insert = (html, fn) => {
  fn = fn || (() => {
  });
  global.pool.query('insert into ' + SQL_TABLE + '(html, time) values(?, ?)', [html.html, html.time], (err, result) => {
    if (err)
      throw err;
    html.htmlId = result.insertId;
    fn()
  })
}

exports.update = (obj, resolve, reject) => {
  resolve = resolve || (() => {
  });
  if (!obj.html_id) {
    reject('缺少html_id')
    return
  }
  var sql = 'update html set html_id=?',
    paras = [obj.html_id];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1 && key != 'html_id') {
      sql += ', ' + key + '=?';
      paras.push(obj[key])
    }
  }
  sql += ' where html_id=?';
  paras.push(obj.html_id)
  zoroDB.query(sql, paras, (err, result) => {
    if (err) {
      reject(err)
      return
    }
    resolve()
  })
}

exports.select = (obj, resolve) => {
  resolve = resolve || (() => {
  });
  var sql = 'select * from html where 1=1',
    paras = [];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1) {
      sql += ' and ' + key + '=?';
      paras.push(obj[key])
    }
  }
  zoroDB.query(sql, paras, (err, rows, fields) => {
    if (err) {
      log(err)
      resolve([])
      return
    }
    rows.forEach(row => {
      exports.fillProp(row)
    })
    resolve(rows)
  })
}

exports.fillProp = html => {
}
